// user.js
var api = require('../../api.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    contact_tel: "",
    show_customer_service: 0,
    tab_detail: "active",
    tab_comment: "",
    tab_other: "",
    myInfo: null,
    show: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {},

  loadData: function(options) {
    var page = this;
    page.setData({
      store: wx.getStorageSync('store'),
      myInfo: wx.getStorageSync('my_info')
    });
    wx.login({
      success: function (res) {
        if (res.code) {
          var code = res.code;
          getApp().loginrequest({
            url: api.passport.quick_login,
            method: "post",
            data: {
              code: code
            },
            success: function (res) {
              console.log("quickLoginSuccessful")
              console.log(res)
              wx.hideLoading();
              if (res.code == 200) {
                const tokenStr = res.data.tokenHead + res.data.token
                wx.setStorageSync('loginToken', tokenStr)
                wx.setStorageSync('token', res.data.token);
                wx.setStorageSync("access_token", res.data.userId);
                wx.setStorageSync("user_info", {
                  avatar_url: res.data.img,
                  nickname: res.data.username,
                  avatar_url: res.data.icon,
                  // parent: res.data.parent,
                  id: res.data.id
                });
                wx.setStorageSync("my_info", {
                  supplyId: res.data.myInfo.supplyId,
                  supplyState: res.data.myInfo.supplyState,
                  myMoney: res.data.myInfo.myMoney,
                  icon: res.data.myInfo.icon,
                  nickname: res.data.myInfo.nickname,
                  memberLevelId: res.data.myInfo.memberLevelId,
                  id: res.data.myInfo.id,
                  city: res.data.myInfo.city,
                  gender: res.data.myInfo.gender,
                  job: res.data.myInfo.job,
                  phone: res.data.myInfo.phone,
                  birthday: res.data.myInfo.birthday,
                  brokerage: res.data.myInfo.brokerage,
                  brokerageTixian: res.data.myInfo.brokerageTixian,

                  moneyTotal: res.data.myInfo.moneyTotal,
                  buyTotal: res.data.myInfo.buyTotal,

                  // parent: res.data.parent,
                });
                page.setData({
                  store: wx.getStorageSync('store'),
                  myInfo: wx.getStorageSync('my_info')
                });
              }
            }
          });
        }


      }
    });
    console.log("myInfo");
    console.log(wx.getStorageSync('my_info'));
    console.log("user_info");
    console.log(wx.getStorageSync('user_info'));
    var access_token = wx.getStorageSync("access_token");
    app.request({
      url: api.user.index,
      data: {
        id: access_token
      },
      success: function(res) {
        if (res.code == 200) {
          page.setData({
            user_info: res.data.user
          });
          page.setData({
            order_count: res.data.count
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var page = this;
    page.loadData();
  },

  callTel: function(e) {
    var tel = e.currentTarget.dataset.tel;
    wx.makePhoneCall({
      phoneNumber: tel, //仅为示例，并非真实的电话号码
    });
  },
  tabSwitch: function(e) {
    var page = this;
    var tab = e.currentTarget.dataset.tab;
    if (tab == "detail") {
      page.setData({
        tab_detail: "active",
        tab_comment: "",
        tab_other: "",
      });
    } else if (tab == "comment") {
      page.setData({
        tab_detail: "",
        tab_comment: "active",
        tab_other: "",

      });
    } else {
      page.setData({
        tab_detail: "",
        tab_comment: "",
        tab_other: "active",
      });
    }
  },
  //申请成为供应商
  apply: function(e) {
    var page = this;
    wx.navigateTo({
      url: '/pages/add-share/index',
    })
  },
  ///分享推广码
  sharecode: function(e) {
    var that = this

    var access_token = wx.getStorageSync("access_token");
    wx.request({
      url: api.order.getQr, //仅为示例，并非真实的接口地址
      data: {
        userId: access_token
      },
      success(res) {
        console.log("res.data")
        console.log(res.data)
        that.setData({
          show: true,
          imgUrl: res.data
        })
      }
    })

  },
  
  ///订阅消息授权
  subscribe() {
    wx.requestSubscribeMessage({
      tmplIds: ['dtmwjr_O8moWsz6Yq0dmY95SoV8csRnbA4xvwQsYL-w','F6oyNZhjaQYOMWdGJcrd6wne7nf0qTr2gH7vaIMmX5k','qZOpyTxHMMB9EibgkUtm5mv9_lkQ09PYvwzdw6-pzqw'],
      success(res) {
        console.log(res)
      }
    })
  },


  onClose() {
    this.setData({
      show: false
    });
  },
  verify: function(e) {
    wx.scanCode({
      onlyFromCamera: false,
      success: function(res) {
        console.log(res)
        wx.navigateTo({
          url: '/' + res.path,
        })
      },
      fail: function(e) {
        wx.showToast({
          title: '失败'
        });
      }
    });
  },
  tapMembership: function(e) {
    wx.navigateTo({
      url: '/pages/user_detail/userdetail',
    })
  },
  tixian: function(e) {
    wx.navigateTo({
      url: '/pages/tixian/tixian',
    })
  },
  yongjin: function(e) {
    wx.navigateTo({
      url: '/pages/assets/index',
    })
  },
  getUserInfo(arg) {
    console.log("获取到的用户信息")
    console.log(arg)
    wx.login({
      success: function(res) {
        if (res.code) {
          console.log("获取到的code")
          console.log(res.code)
          getApp().loginrequest({
            url: api.passport.login,
            method: "post",
            data: {
              code: res.code,
              userInfo: arg.detail.rawData,
              encrypted_data: arg.detail.encryptedData,
              iv: arg.detail.iv,
              signature: arg.detail.signature
            },
            success: function(res) {
              console.log("真正的登陆成功userlogin")
              console.log(res)
              wx.hideLoading();
              if (res.code == 200) {
                const tokenStr = res.data.tokenHead + res.data.token
                wx.setStorageSync('loginToken', tokenStr)
                wx.setStorageSync('token', res.data.token);
                wx.setStorageSync("access_token", res.data.userId);
                wx.setStorageSync("user_info", {
                  avatar_url: res.data.img,
                  nickname: res.data.username,
                  avatar_url: res.data.icon,
                  // parent: res.data.parent,
                  id: res.data.userId
                });
                wx.setStorageSync("my_info", {
                  supplyId: res.data.myInfo.supplyId,
                  supplyState: res.data.myInfo.supplyState,
                  myMoney: res.data.myInfo.myMoney,
                  icon: res.data.myInfo.icon,
                  nickname: res.data.myInfo.nickname,
                  memberLevelId: res.data.myInfo.memberLevelId,
                  id: res.data.myInfo.id,
                  city: res.data.myInfo.city,
                  gender: res.data.myInfo.gender,
                  job: res.data.myInfo.job,
                  phone: res.data.myInfo.phone,
                  birthday: res.data.myInfo.birthday,



                  // parent: res.data.parent,
                });

                var parent_id = wx.getStorageSync("parent_id");
                var p = getCurrentPages();
                // var parent_id = 0;


                if (p[0].options.user_id != undefined) {

                  parent_id = p[0].options.user_id;
                } else if (p[0].options.scene != undefined) {
                  parent_id = p[0].options.scene;
                }
            

                if (page == undefined) {
                  return;

                }
                wx.redirectTo({
                  url: "/" + page.route + "?" + util.objectToUrlParams(page.options),
                  fail: function() {
                    wx.switchTab({
                      url: "/" + page.route,
                    });
                  },
                });
              } else {
                // wx.showToast({
                //   title: res.msg
                // });
              }
            }
          });
        }


      }
    });
    if (arg.detail.iv) {
      console.log("6666666")
      console.log(arg.detail)
      if (wx.reLaunch) {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      } else {
        this.location('/pages/index/index');
      }
      //   app.locationReplace('/pages/index/index');
    }
  }
});